package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.amazonaws.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Response;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Result;
import com.zbkj.dal.base.constants.OrderConstants;
import com.zbkj.dal.base.constants.PayConstants;
import com.zbkj.dal.base.constants.UserConstants;
import com.zbkj.dal.base.constants.WeChatConstants;
import com.zbkj.dal.base.enums.*;
import com.zbkj.dal.common.exception.CrmebException;
import com.zbkj.dal.common.utils.CrmebDateUtil;
import com.zbkj.dal.common.utils.CrmebUtil;
import com.zbkj.dal.common.utils.WxPayUtil;
import com.zbkj.dal.dao.ShareProfitRecordDao;
import com.zbkj.dal.dao.partner.PartnerRoleCardDao;
import com.zbkj.dal.dao.partner.PartnerRoleCardPayLogDao;
import com.zbkj.dal.dao.partner.PartnerRoleDao;
import com.zbkj.dal.dao.partner.PartnerRoleProfitDao;
import com.zbkj.dal.entity.order.DuesOrder;
import com.zbkj.dal.entity.partner.PartnerRole;
import com.zbkj.dal.entity.partner.PartnerRoleCard;
import com.zbkj.dal.entity.partner.PartnerRoleCardPayLog;
import com.zbkj.dal.entity.partner.PartnerRoleProfit;
import com.zbkj.dal.entity.profit.ShareProfitRecord;
import com.zbkj.dal.entity.user.User;
import com.zbkj.dal.entity.user.UserToken;
import com.zbkj.dal.entity.wechat.WechatPayInfo;
import com.zbkj.dal.pojo.request.CreateDuesOrderRequest;
import com.zbkj.dal.pojo.response.CreateDuesOrderResponse;
import com.zbkj.dal.pojo.response.partner.PartnerRoleResponse;
import com.zbkj.dal.pojo.vo.AttachVo;
import com.zbkj.dal.pojo.vo.CreateOrderRequestVo;
import com.zbkj.dal.pojo.vo.CreateOrderResponseVo;
import com.zbkj.service.manager.FundManager;
import com.zbkj.service.manager.ShareProfitManager;
import com.zbkj.service.model.dto.FundUpdateDTO;
import com.zbkj.service.model.dto.pay.UnifiedorderDTO;
import com.zbkj.service.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class PartnerRoleServiceImpl extends ServiceImpl<PartnerRoleDao, PartnerRole> implements PartnerRoleService {

    private final Logger logger = LoggerFactory.getLogger(PartnerRoleServiceImpl.class);

    @Resource
    private UserServiceImpl userService;

    @Resource
    private PartnerRoleDao partnerRoleDao;

    @Resource
    private ShareProfitRecordDao shareProfitRecordDao;

    @Resource
    private PartnerRoleProfitDao partnerRoleProfitDao;

    @Resource
    private PartnerRoleCardDao partnerRoleCardDao;

    @Resource
    private PartnerRoleCardPayLogDao partnerRoleCardPayLogDao;

    @Resource
    private PayServiceImpl payService;

    @Resource
    private WechatServiceImpl wechatService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private UserTokenService userTokenService;

    @Autowired
    private ShareProfitManager shareProfitManager;

    @Resource
    private FundManager fundManager;

    @Resource
    private DuesOrderService duesOrderService;

    @Resource
    private WechatPayInfoService wechatPayInfoService;

    private static final DateTimeFormatter EXPIRE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss+08:00").withZone(ZoneId.of("Asia/Shanghai"));

    /**
     * 查询卡片的权益
     *
     * @param roleId
     * @return
     */
    private List<PartnerRoleProfit> listPartnerRoleProfit(Integer roleId) {
        LambdaQueryWrapper<PartnerRoleProfit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PartnerRoleProfit::getIsDel, false);
        lambdaQueryWrapper.eq(PartnerRoleProfit::getRoleId, roleId);
        lambdaQueryWrapper.orderByAsc(PartnerRoleProfit::getSort);
        return partnerRoleProfitDao.selectList(lambdaQueryWrapper);
    }

    /**
     * 合伙人角色卡列表
     *
     * @return
     */
    @Override
    public List<PartnerRoleResponse> listUserPartnerRole() {
        User user = userService.getInfo();
        if (user == null) {
            throw new CrmebException("用户登录超时");
        }

        //查询用户当前角色卡
        PartnerRole udserPartnerRole = null;
        if (user.getIsPartnerRole() && user.getPartnerRoleId() != null) {
            udserPartnerRole = partnerRoleDao.selectById(user.getPartnerRoleId());
            logger.info("udserPartnerRole>>>>{}", JSON.toJSONString(udserPartnerRole));
        }

        //查询所有角色卡
        List<PartnerRoleResponse> partnerRoleResponseList = new ArrayList<>();
        LambdaQueryWrapper<PartnerRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PartnerRole::getIsDel, false);
        lambdaQueryWrapper.orderByAsc(PartnerRole::getPaymentAmount); //根据售价排序
        List<PartnerRole> partnerRoleList = partnerRoleDao.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(partnerRoleList)) {
            return partnerRoleResponseList;
        }
        for (PartnerRole partnerRole : partnerRoleList) {
            //判断卡等级
            PartnerRoleResponse roleResponse = JSON.parseObject(JSON.toJSONString(partnerRole), PartnerRoleResponse.class);
            roleResponse.setCardStatus("DEF");
            roleResponse.setButtonName("开启雅士");
            if (udserPartnerRole != null) {
                if (partnerRole.getId().equals(udserPartnerRole.getId())) {
                    roleResponse.setCardStatus("NOW");
                    roleResponse.setButtonName("续费雅士");
                } else if (udserPartnerRole.getPaymentAmount().intValue() < partnerRole.getPaymentAmount().intValue()) {
                    roleResponse.setCardStatus("OVER");
                    roleResponse.setButtonName("升级雅士");
                } else if (udserPartnerRole.getPaymentAmount().intValue() > partnerRole.getPaymentAmount().intValue()) {
                    roleResponse.setCardStatus("LOW");
                    roleResponse.setButtonName("开启雅士");
                    continue;
                }
            }

            //会员卡权益
            roleResponse.setPartnerRoleProfits(this.listPartnerRoleProfit(partnerRole.getId()));
            partnerRoleResponseList.add(roleResponse);
        }
        return partnerRoleResponseList;
    }

    /**
     * 购买角色卡
     */
    @Override
    @Transactional
    public String bayPartnerRoleCard(Integer roleId) {
        Assert.isTrue(roleId != null, "参数错误，角色卡ID为空");

        User user = userService.getInfo();
        if (user == null) {
            throw new CrmebException("用户登录超时");
        }

        PartnerRole partnerRole = partnerRoleDao.selectById(roleId);
        if (partnerRole == null) {
            throw new CrmebException("角色卡查询失败");
        }

        //用户开卡记录
        PartnerRoleCard partnerRoleCard = null;
        LambdaQueryWrapper<PartnerRoleCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PartnerRoleCard::getUserId, user.getId());
        lambdaQueryWrapper.eq(PartnerRoleCard::getRoleId, partnerRole.getId());
        lambdaQueryWrapper.ne(PartnerRoleCard::getCardStatus, "CLOSE");
        lambdaQueryWrapper.last("limit 1");
        partnerRoleCard = partnerRoleCardDao.selectOne(lambdaQueryWrapper);
        if (partnerRoleCard == null) {
            partnerRoleCard = new PartnerRoleCard();
            partnerRoleCard.setUserId(user.getId());
            partnerRoleCard.setRoleId(partnerRole.getId());
            partnerRoleCard.setRoleName(partnerRole.getName());
            partnerRoleCard.setCardStartTime(new Date());
            partnerRoleCard.setCardStatus("WAIT_PAY");
            partnerRoleCard.setCardImg(partnerRole.getBgImage());
            partnerRoleCard.setShareProfitLevel(partnerRole.getShareProfitLevel());
            String accountNo = CrmebUtil.getOrderNo(OrderConstants.PARTNER_ROLE_PLATFORM);
            partnerRoleCard.setAccountNo(accountNo);
            partnerRoleCard.setUserPartnerRoleLevel(partnerRole.getCardLevel());
            partnerRoleCardDao.insert(partnerRoleCard);
        }

        //自动开启会员充值
        /*CreateDuesOrderRequest createDuesOrderRequest = new CreateDuesOrderRequest();
        createDuesOrderRequest.setPrice(new BigDecimal(10000));
        CreateDuesOrderResponse createDuesOrderResponse = duesOrderService.createDuesOrder(createDuesOrderRequest);
        logger.info("createDuesOrderResponse>>>>>{}", JSON.toJSONString(createDuesOrderResponse));
        if (StringUtils.isBlank(createDuesOrderResponse.getOrderNo())) {
            throw new CrmebException("会员充值创建失败");
        }*/

        //创建支付流水
        PartnerRoleCardPayLog partnerRoleCardPayLog = new PartnerRoleCardPayLog();
        partnerRoleCardPayLog.setRoleId(roleId);
        partnerRoleCardPayLog.setUserId(user.getId());
        partnerRoleCardPayLog.setRoleCardId(partnerRoleCard.getId());
        partnerRoleCardPayLog.setRoleCardNo(null);//会员卡号 支付成功回填
        partnerRoleCardPayLog.setPayAmount(partnerRole.getPaymentAmount());
        partnerRoleCardPayLog.setCreateTime(new Date());
        LocalDateTime expireTime = LocalDateTime.now().plusHours(15);
        partnerRoleCardPayLog.setExpiredTime(expireTime.format(EXPIRE_TIME_FORMATTER));
        partnerRoleCardPayLog.setPayStatus("WAIT");
        partnerRoleCardPayLog.setPayChannel("WXPAY");
        String payNo = CrmebUtil.getOrderNo(OrderConstants.ORDER_PARTNER_ROLE_PLATFORM);
        partnerRoleCardPayLog.setPayNo(payNo);
        //partnerRoleCardPayLog.setDuesOrderNo(createDuesOrderResponse.getOrderNo());
        partnerRoleCardPayLogDao.insert(partnerRoleCardPayLog);
        return payNo;
    }

    /**
     * 生成微信预支付 返回支付参数 小程序拉起支付
     *
     * @param payNo
     * @return
     */
    @Override
    public Map<String, String> payPartnerRoleCard(String payNo) {
        Assert.isTrue(StringUtils.isNotBlank(payNo), "支付参数错误 payNo is null");
        User user = userService.getInfo();
        if (user == null) {
            throw new CrmebException("用户登录超时");
        }

        PartnerRoleCardPayLog partnerRoleCardPayLog = this.getPartnerRoleCardPayLogByNo(payNo);
        if (partnerRoleCardPayLog == null) {
            throw new CrmebException("支付参数错误");
        }

        if (partnerRoleCardPayLog.getPayAmount().intValue() <= 0) {
            throw new CrmebException("支付金额错误");
        }

        // 小程序Token
        UserToken userToken = userTokenService.getTokenByUserId(user.getId(), UserConstants.USER_TOKEN_TYPE_ROUTINE);
        userToken.setToken(userToken.getToken());

        // 获取appid、mch_id、微信签名key
        String appId = systemConfigService.getValueByKeyException(WeChatConstants.WECHAT_MINI_APPID);
        String mchId = systemConfigService.getValueByKeyException(WeChatConstants.WECHAT_PAY_MINI_MCHID);
        String signKey = systemConfigService.getValueByKeyException(WeChatConstants.WECHAT_PAY_MINI_KEY);

        // 获取微信预下单对象
        UnifiedorderDTO order = new UnifiedorderDTO();
        order.setUid(user.getId());
        order.setPayChannel(PayConstants.WX_PAY_TRADE_TYPE_JS);
        order.setPayPrice(partnerRoleCardPayLog.getPayAmount());
        order.setAttachVoPayType("card");

        CreateOrderRequestVo unifiedorderVo = payService.getUnifiedorderVo(payNo, order, userToken.getToken(), appId, mchId, signKey);
        // 预下单（统一下单）
        CreateOrderResponseVo responseVo = wechatService.payUnifiedorder(unifiedorderVo);
        // 组装前端预下单参数
        Map<String, String> map = new HashMap<>();
        map.put("appId", unifiedorderVo.getAppid());
        map.put("nonceStr", responseVo.getNonceStr());
        map.put("package", "prepay_id=".concat(responseVo.getPrepayId()));
        map.put("signType", "RSA");
        Long currentTimestamp = WxPayUtil.getCurrentTimestamp();
        map.put("timeStamp", Long.toString(currentTimestamp));
        map.put("paySign", responseVo.getSign());
        map.put("prepayId", responseVo.getPrepayId());
        map.put("prepayTime", CrmebDateUtil.nowDateTimeStr());
        map.put("outTradeNo", unifiedorderVo.getOut_trade_no());
        logger.info("map >>>>{}", JSON.toJSONString(map));
        return map;
    }

    /**
     * 通过卡号获取用户角色卡
     *
     * @param payNo
     * @return
     */
    public PartnerRoleCardPayLog getPartnerRoleCardPayLogByNo(String payNo) {
        LambdaQueryWrapper<PartnerRoleCardPayLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PartnerRoleCardPayLog::getPayNo, payNo);
        lambdaQueryWrapper.last("limit 1");
        return partnerRoleCardPayLogDao.selectOne(lambdaQueryWrapper);
    }

    /**
     * 通过卡号获取用户角色卡
     *
     * @param orderNo
     * @return
     */
    private PartnerRoleCard getPartnerRoleCardByNo(String orderNo) {
        LambdaQueryWrapper<PartnerRoleCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PartnerRoleCard::getCardNo, orderNo);
        lambdaQueryWrapper.last("limit 1");
        return partnerRoleCardDao.selectOne(lambdaQueryWrapper);
    }

    @Override
    public void test() {
        AttachVo attachVo = new AttachVo();
        attachVo.setType("card");
        attachVo.setUserId(183);
        paySuccessDealCard(null, "BBSH161173717001681884388", attachVo);
    }

    private Integer getPartnerRoleCardCount(Integer roleId) {
        LambdaQueryWrapper<PartnerRoleCard> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PartnerRoleCard::getCardStatus, "USE");
        lambdaQueryWrapper.eq(PartnerRoleCard::getRoleId, roleId);
        return partnerRoleCardDao.selectCount(lambdaQueryWrapper);
    }

    /**
     * 购卡支付成功之后 处理卡片
     *
     * @param result
     * @param outTradeNo
     * @param attachVo
     */
    @Transactional
    public void paySuccessDealCard(WxPayNotifyV3Result.DecryptNotifyResult result, String outTradeNo, AttachVo attachVo) {
        //支付成功 1.修改支付流水状态 2.修改卡片状态 3.修改用户角色卡状态
        PartnerRoleCardPayLog partnerRoleCardPayLog = this.getPartnerRoleCardPayLogByNo(outTradeNo);
        if (ObjectUtil.isNull(partnerRoleCardPayLog) || !partnerRoleCardPayLog.getUserId().equals(attachVo.getUserId())) {
            logger.error("订单{}回调信息处理失败，未查询到对应的订单信息", outTradeNo);
            throw new CrmebException(String.format("订单%s不存在", outTradeNo));
        }

        //编辑支付角色卡支付流水
        PartnerRoleCardPayLog savePartnerRoleCardPayLog = new PartnerRoleCardPayLog();
        savePartnerRoleCardPayLog.setId(partnerRoleCardPayLog.getId());
        Date payTime = this.parseDate(result.getSuccessTime(), null);
        savePartnerRoleCardPayLog.setPayTime(payTime);
        savePartnerRoleCardPayLog.setThirdPayNo(result.getTransactionId());
        savePartnerRoleCardPayLog.setPayTime(new Date());
        partnerRoleCardPayLogDao.updateById(savePartnerRoleCardPayLog);

        //编辑用户角色卡
        PartnerRoleCard partnerRoleCard = partnerRoleCardDao.selectById(partnerRoleCardPayLog.getRoleCardId());
        if (partnerRoleCard == null) {
            throw new CrmebException(String.format("订单%s不存在", outTradeNo));
        }

        //卡片查询
        PartnerRole partnerRole = partnerRoleDao.selectById(partnerRoleCard.getRoleId());
        if (partnerRole == null) {
            throw new CrmebException("角色卡查询失败");
        }

        //编辑会员会员卡 回填卡号
        PartnerRoleCard savePartnerRoleCard = new PartnerRoleCard();
        savePartnerRoleCard.setId(partnerRoleCard.getId());
        savePartnerRoleCard.setCardStatus("USE");
        String cardNo = CrmebUtil.getIntAccountNo(partnerRoleCard.getRoleName(), this.getPartnerRoleCardCount(partnerRole.getId()));
        savePartnerRoleCard.setCardNo(cardNo);

        // 获取当前日期和时间
        Date currentDate = partnerRoleCard.getCardEndTime() == null ? new Date() : partnerRoleCard.getCardEndTime();

        // 使用Calendar增加一年
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.YEAR, 1);

        // 获取修改后的日期
        Date newDate = calendar.getTime();
        savePartnerRoleCard.setCardEndTime(newDate); //支付成功,到期时间增加1年
        savePartnerRoleCard.setUserPartnerRoleLevel(partnerRole.getShareProfitLevel());
        partnerRoleCardDao.updateById(savePartnerRoleCard);

        //编辑用户
        User user = userService.getById(partnerRoleCardPayLog.getUserId());
        if (user == null) {
            throw new CrmebException("用户查询失败");
        }
        User saveUser = new User();
        saveUser.setId(user.getId());
        if ("L001".equals(partnerRoleCard.getShareProfitLevel())) {
            saveUser.setFirstPromoter(true);
        } else if ("L002".equals(partnerRoleCard.getShareProfitLevel())) {
            saveUser.setFirstPromoter(true);
            saveUser.setSecondPromoter(true);
        }
        saveUser.setPartnerRoleCode(cardNo);
        saveUser.setIsPromoter(true);
        saveUser.setEnableShareProfit(1);
        saveUser.setIsPartnerRole(true);
        saveUser.setPartnerRoleId(partnerRole.getId());
        saveUser.setUserPartnerRoleId(partnerRoleCard.getId());
        saveUser.setUserPartnerRoleLevel(partnerRole.getShareProfitLevel());
        userService.updateById(saveUser);

        //处理呈享订单
        //this.duesOrder(outTradeNo, partnerRoleCardPayLog.getDuesOrderNo(), this.formatDate(payTime, null), result.getTransactionId());

        List<ShareProfitRecord> shareProfitRecords = new ArrayList<>();
        //一级分润
        //分润初始化
        String orderNo = partnerRoleCardPayLog.getPayNo();
        String image = partnerRoleCard.getCardImg();
        BigDecimal proTotalPrice = partnerRoleCardPayLog.getPayAmount();

        //查询上级分销人
        User oneUser = userService.getById(user.getSpreadUid());
        if (oneUser != null) {
            //卡片查询
            PartnerRole oneUserPartnerRole = partnerRoleDao.selectById(oneUser.getPartnerRoleId());
            logger.info("oneUserPartnerRole>>>>>{}", JSON.toJSONString(oneUserPartnerRole));
            if (oneUserPartnerRole != null) {
                //查询上级分销角色卡
                BigDecimal residualAmount = new BigDecimal(0);
                if ("L001".equals(partnerRole.getCardLevel())) { //普通会员
                    residualAmount = oneUserPartnerRole.getParentReferrerAwardOne();
                } else if ("L002".equals(partnerRole.getCardLevel())) { //合伙人
                    residualAmount = oneUserPartnerRole.getParentReferrerAwardTwo();
                } else if ("L003".equals(partnerRole.getCardLevel())) { //加盟店
                    residualAmount = oneUserPartnerRole.getParentReferrerAwardThree();
                }

                ShareProfitRecord oneShareProfitRecord = this.shareProfitRecord("L001", oneUser, image, proTotalPrice, residualAmount, outTradeNo);
                shareProfitRecordDao.insert(oneShareProfitRecord);
                shareProfitRecords.add(oneShareProfitRecord);
            }
        }

        //二级分润
        if (oneUser != null) {
            User twoUser = userService.getById(oneUser.getSpreadUid());
            if (twoUser != null) {
                //卡片查询
                PartnerRole oneUserPartnerRole = partnerRoleDao.selectById(twoUser.getPartnerRoleId());
                if (oneUserPartnerRole != null) {
                    //查询上级分销角色卡
                    BigDecimal residualAmount = new BigDecimal(0);
                    if ("L001".equals(partnerRole.getCardLevel())) { //普通会员
                        residualAmount = oneUserPartnerRole.getOneReferrerAwardOne();
                    } else if ("L002".equals(partnerRole.getCardLevel())) { //合伙人
                        residualAmount = oneUserPartnerRole.getOneReferrerAwardTwo();
                    } else if ("L003".equals(partnerRole.getCardLevel())) { //加盟店
                        residualAmount = oneUserPartnerRole.getOneReferrerAwardThree();
                    }
                    ShareProfitRecord twoShareProfitRecord = this.shareProfitRecord("L002", twoUser, image, proTotalPrice, residualAmount, outTradeNo);
                    shareProfitRecordDao.insert(twoShareProfitRecord);
                    shareProfitRecords.add(twoShareProfitRecord);
                }
            }
        }

        // 雅识添加申请
        for (ShareProfitRecord shareProfitRecord : shareProfitRecords) {
            // 店铺、贝贝奢护目前不进行任何操作,只记录信息
            if (Objects.equals(SharePayeeTypeEnums.USER.name(), shareProfitRecord.getPayeeType()) && shareProfitRecord.getRealAmount() != null && shareProfitRecord.getRealAmount().compareTo(BigDecimal.ZERO) != 0) {
                fundManager.addCrabRoeApply(FundUpdateDTO.generateShareProfit(shareProfitRecord));
            }
        }

        if (CollectionUtil.isNotEmpty(shareProfitRecords)) {
            //分销提交
            shareProfitManager.shareProfitConfirmAsync(orderNo);
        }
    }

    private void duesOrder(String payNo, String outTradeNo, String timeEnd, String transactionId) {
        DuesOrder duesOrder = duesOrderService.getByOrderNo(outTradeNo);
        if (ObjectUtil.isNull(duesOrder)) {
            logger.error("会费充值订单后置处理，没有找到对应订单，支付服务方订单号：{}", outTradeNo);
            throw new CrmebException("没有找到充值订单信息");
        }
        /*if (!Objects.equals(duesOrder.getPaid(), DuesStatusEnums.UNPAID.getCode())) {
            throw new CrmebException("支付状态错误");
        }*/
        WechatPayInfo wechatPayInfo = wechatPayInfoService.getByNo(payNo);
        if (ObjectUtil.isNull(wechatPayInfo)) {
            logger.error("会费充值订单{}回调结果处理失败，未查询到对应的订单信息", outTradeNo);
            throw new CrmebException(String.format("未查询到会费充值订单%s", outTradeNo));
        }
//                wechatPayInfo.setIsSubscribe(callbackVo.getIsSubscribe());
        wechatPayInfo.setBankType("weixin");
        wechatPayInfo.setCashFee(duesOrder.getPrice().intValue());
        wechatPayInfo.setCouponFee(0);
        wechatPayInfo.setTransactionId(transactionId);
        wechatPayInfo.setTimeEnd(timeEnd);

        Boolean successAfter = duesOrderService.paySuccessAfter(duesOrder, wechatPayInfo);
        if (!successAfter) {
            logger.error("会费充值订单{}回调结果处理失败，保存回调结果失败", outTradeNo);
            throw new CrmebException(String.format("会费充值订单%s回调结果保存失败", outTradeNo));
        }
    }

    public Date parseDate(String dateValue, String dateFormat) {
        if (dateValue == null) {
            throw new IllegalArgumentException("dateValue is null");
        }

        if (dateFormat == null) {
            dateFormat = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat df = new SimpleDateFormat(dateFormat);
        Date result = null;

        try {
            result = df.parse(dateValue);
        } catch (Exception pe) {

        }
        return result;
    }

    public String formatDate(Date date, String pattern) {
        if (date == null) {
            return "";
        }

        if (pattern == null) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }

        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    /**
     * 初始化分润
     *
     * @param user
     * @param image
     * @param proTotalPrice
     * @param residualAmount
     * @param outTradeNo
     * @return
     */
    private ShareProfitRecord shareProfitRecord(String shareProfitLevel, User user, String image, BigDecimal proTotalPrice, BigDecimal residualAmount, String outTradeNo) {
        ShareProfitRecord shareProfitRecord = new ShareProfitRecord();
        shareProfitRecord.setShareProfitNo(CrmebUtil.getOrderNo(OrderConstants.CRAB_ROE_ACCOUNT_PREFIX));
        shareProfitRecord.setPayeeCode(user.getId().toString());
        shareProfitRecord.setPayeeType(SharePayeeTypeEnums.USER.name());
        shareProfitRecord.setSourceUserId(user.getId());
        shareProfitRecord.setSourceUserName(user.getNickname());
        shareProfitRecord.setShareParty("L001".equals(shareProfitLevel) ? SharePartyEnums.DIRECT_REFERRER.getCode() : SharePartyEnums.INDIRECT_REFERRER.getCode());
        shareProfitRecord.setImagePath(image);
        shareProfitRecord.setSceneCode(ShareProfitSceneEnums.RECRUIT.getCode());
        shareProfitRecord.setBillDate(LocalDate.now());
        shareProfitRecord.setBizOrderNo(outTradeNo);
        shareProfitRecord.setShareModel(ShareModelEnums.FIXED.getCode());
        shareProfitRecord.setOrderAmount(proTotalPrice);
        shareProfitRecord.setShareAmount(residualAmount);
        shareProfitRecord.setRoleAmount(residualAmount);
        shareProfitRecord.setRealAmount(residualAmount);
        shareProfitRecord.setShareStatus(ShareSettleStatusEnums.WAIT_SETTLE.getCode());
        shareProfitRecord.setRemark("L001".equals(shareProfitLevel)
                ? String.format("新用户购卡直接分润奖励金额【%s】", residualAmount) :
                String.format("新用户购卡团分润奖励金额【%s】", residualAmount));
        shareProfitRecord.setCreateTime(LocalDateTime.now());
        shareProfitRecord.setDeleted(BooleanEnums.FALSE.getCode());
        return shareProfitRecord;
    }
}
